package com.yld.oa.employee.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.yld.oa.employee.dao.EmployeeDao;
import com.yld.oa.employee.entity.EmployeeEntity;
import com.yld.util.DBUtil;
import com.yld.util.SingleConnection;

public class EmployeeDaoImpl implements EmployeeDao {

	@Override
	public void addEmployee(EmployeeEntity employee) {
		
		Connection connection  = SingleConnection.getConnection();
		System.out.println("EmployeeDao connection"+connection);
		
		//2 准备sql 占位符
		String sql ="INSERT INTO OA_EMPLOYEE_T(ID,EMPLOYEE_NAME,DEPARTMENT_ID) VALUES(?,?,?)";
		
		PreparedStatement ps = null;
		
		try {
			//3把字符串封装成可执行的sql命令    准备好的执行语句
			ps = connection.prepareStatement(sql);
			
			//4对参数给定具体的值
			ps.setInt(1, employee.getId());
			ps.setString(2, employee.getEmployeeName());
			ps.setInt(3, employee.getDepartmentId());
			
			//5执行命令
			ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			DBUtil.closePreparedStatement(ps);
			//DBUtil.closeConnection(connection);
		}

	}


	/**
	 * 通过部门id查找下面的员工s
	 * @param departmentId
	 * @return
	 */
	@Override
	public List<EmployeeEntity> findByDepartmentId(Integer departmentId) {
		
		List<EmployeeEntity>  employees= new ArrayList<EmployeeEntity>();
		
		Connection connection= SingleConnection.getConnection();
		
		
		String sql = " select ID AS id,EMPLOYEE_NAME AS employeeName ,DEPARTMENT_ID AS departmentId"
					+ " from oa_employee_t where DEPARTMENT_ID=?";
		
		try {
			PreparedStatement ps = connection.prepareStatement(sql);
			
			ps.setInt(1, departmentId);
			ResultSet rs = ps.executeQuery();
			
			while (rs.next()) {
				EmployeeEntity emp=new EmployeeEntity();
				emp.setId(rs.getInt("id"));
				emp.setEmployeeName(rs.getString("employeeName"));
				emp.setDepartmentId(rs.getInt("departmentId"));
				employees.add(emp);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		
		
		return employees;
	}

}
